package com.jtpay.sdk.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.jtpay.sdk.R;
import com.jtpay.sdk.adapter.UserNamePopAdapter;
import com.jtpay.sdk.base.BaseActivity;
import com.jtpay.sdk.entity.UserModel;
import com.jtpay.sdk.manager.DBManager;
import com.jtpay.sdk.util.SharedPreferencesManager;
import com.jtpay.sdk.weight.PlatFromPop;
import com.jtpay.sdk.weight.UserNamePop;

import java.util.ArrayList;
import java.util.List;

import apiUtils.apis.GetAppInfoAPI;
import apiUtils.models.PayAppInfo;
import apiUtils.models.PayInfo;
import apiUtils.models.PayPlatFormModel;
import appUtils.ToastUtil;
import butterknife.Bind;
import butterknife.OnClick;
import constant.ApiConstants;

public class LoginActivity extends BaseActivity implements UserNamePopAdapter.ItemClickListener, UserNamePop.BottomClickListener {
    @Bind(R.id.username_et)
    EditText mUsernameEt;
    @Bind(R.id.password_et)
    EditText mPasswordEt;
    @Bind(R.id.platform_name_textview)
    TextView mPlatformNameTv;
    @Bind(R.id.remember_cb)
    CheckBox mRememberCb;
    @Bind(R.id.button_login)
    Button mButtonLogin;
    @Bind(R.id.username_pop_ib)
    ImageButton mUserNamePopIb;
    private List<PayPlatFormModel> mPayPlatFormModels = new ArrayList<>();
    private List<PayAppInfo> mPayAppInfos = new ArrayList<>();
    private List<UserModel> mUserModels = new ArrayList<>();
    private PayPlatFormModel mPayPlatFormModel;
    private PlatFromPop mPlatFromPop;
    private UserNamePop mPopupWindow;
    private UserModel mUser;
    private DBManager mDBManager;

    @Override
    protected void initView() {
        mPopupWindow = new UserNamePop(mUserModels, this, this);
        mPopupWindow.setListener(this);
        mPlatFromPop = new PlatFromPop(mPayPlatFormModels, this);
        mPlatFromPop.setOnItemClickListener(popmenuItemClickListener);
        initUser();
        if (mPayPlatFormModels != null && !mPayPlatFormModels.isEmpty() && mPayPlatFormModel == null) {
            mPayPlatFormModel = mPayPlatFormModels.get(0);
        }
        initPlatForm(mPayPlatFormModel.getPtName());
    }

    AdapterView.OnItemClickListener popmenuItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mPayPlatFormModel = mPayPlatFormModels.get(position);
            initPlatForm(mPayPlatFormModel.getPtName());
            mPlatFromPop.dismiss();
            initUserModel();
            initUser();
        }
    };

    private void initPlatForm(String ptname) {
        mPlatformNameTv.setText(ptname);
        ApiConstants.setDefaultUrl(mPayPlatFormModel.getPtUrl());
    }

    @Override
    protected void onStart() {
        super.onStart();
        PayInfo.getInstance().resetAES();
        initUserModel();
        mUser = new UserModel(mUser.getUserName(), mUser.getPassWord(), mUser.getPlatformName(), mUser.getRememberState());
    }

    private void initUser() {
        mRememberCb.setChecked(mUser.getRememberState());
        mUsernameEt.setText(mUser.getUserName());
        mUsernameEt.setSelection(mUsernameEt.length());
        mPasswordEt.setText(mUser.getPassWord());
        mPasswordEt.setSelection(mPasswordEt.length());
        for (int i = 0; i < mPayPlatFormModels.size(); i++) {
            if (mPayPlatFormModels.get(i).getPtName().equals(mUser.getPlatformName())) {
                mPayPlatFormModel = mPayPlatFormModels.get(i);
            }
        }
    }

    @Override
    protected void initData() {
        mPayPlatFormModels.addAll(PayInfo.getInstance().getPayPlatFormModels());
        mDBManager = DBManager.getInstance(this);
        final long userId = mSharedPreferencesManager.readLong(SharedPreferencesManager.USER_ID, -1);
        final UserModel user = mDBManager.queryUserById(userId);
        if (user == null) {
            mUser = new UserModel();
        } else {
            mUser = new UserModel(user.getUserName(), user.getPassWord(), user.getPlatformName(), user.getRememberState());
        }
    }

    private void initUserModel() {
        final List<UserModel> userModels = mDBManager.queryUserList(mPayPlatFormModel.getPtName());
        if (userModels == null || userModels.isEmpty()) {
            mUserNamePopIb.setVisibility(View.INVISIBLE);
            return;
        }
        mUserNamePopIb.setVisibility(View.VISIBLE);
        mUserModels.clear();
        mUserModels.addAll(userModels);
        mPopupWindow.notifyDataSetChanged();
        for (UserModel model : userModels) {
            if (mUser.getUserName().equals(model.getUserName())) {
                mUser = new UserModel(model.getUserName(), model.getPassWord(), model.getPlatformName(), model.getRememberState());
                initUser();
            }
        }
    }

    @OnClick({R.id.button_login, R.id.username_pop_ib, R.id.platform_name_textview})
    void buttonClick(View view) {
        switch (view.getId()) {
            case R.id.button_login:
                login();
                break;
            case R.id.username_pop_ib:
                mPopupWindow.showAtLocation(view);
                break;
            case R.id.platform_name_textview:
                mPlatFromPop.showAsDropDown(view, mUserNamePopIb.getWidth());
                break;
        }
    }

    @Override
    protected int setView() {
        return R.layout.activity_login;
    }

    private void login() {
        final String userName = mUsernameEt.getText().toString();
        final String password = mPasswordEt.getText().toString();
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
            ToastUtil.showShort(getString(R.string.userNameOrPasswordTips));
            mUsernameEt.requestFocus();
            return;
        }
        showProgress(R.string.get_list_of_appinfo);
        new GetAppInfoAPI().getAppInfoAPI(userName, password, new GetAppInfoAPI.Listener() {
            @Override
            public void onSuccess(List<PayAppInfo> payAppInfoList) {
                if (payAppInfoList.size() > 0) {
                    dismisProgress();
                    mPayAppInfos.clear();
                    mPayAppInfos.addAll(payAppInfoList);
                    PayInfo.getInstance().setPayAppInfos(payAppInfoList);
                    startActivity();
                    mUser.setPlatformName(mPlatformNameTv.getText().toString());
                    mUser.setUserName(userName);
                    mUser.setRememberState(mRememberCb.isChecked());
                    mUser.setPassWord(mRememberCb.isChecked() ? password : "");
                    final long userid = mDBManager.insertUser(mUser, mUserModels);
                    PayInfo.getInstance().setPaySystemId(mPayPlatFormModel.getPtCode());
                    mSharedPreferencesManager.saveLong(SharedPreferencesManager.USER_ID, userid);
                }
            }

            @Override
            public void onFailure(int code, String message) {
                dismisProgress();
                ToastUtil.showShort(getString(R.string.login_failed));
            }
        });
    }

    private void startActivity() {
        Intent intent = new Intent(LoginActivity.this, OrderActivity.class);
        startActivity(intent);
    }

    @Override
    public void textContentClick(UserModel model) {
        mUser = model;
        initUser();
        mPopupWindow.dismiss();
    }

    @Override
    public void rightButtonClick(UserModel model) {
        mDBManager.deleteUser(model);
        mUserModels.remove(model);
        mPopupWindow.notifyDataSetChanged();
    }

    @Override
    public void cleanClick() {
        for (UserModel model : mUserModels) {
            mDBManager.deleteUser(model);
        }
        mUserModels.clear();
        mPopupWindow.notifyDataSetChanged();
        mPopupWindow.dismiss();
        mUserNamePopIb.setVisibility(View.INVISIBLE);
    }
}